package com.szh.cloud.login.service.impl;

import com.szh.cloud.login.entity.LoginUserEntity;
import com.szh.cloud.login.entity.MenuLevelEntity;
import com.szh.cloud.login.repository.LoginDao;
import com.szh.cloud.login.service.LoginService;
import com.szh.cloud.mybatis.entity.PtMenuEntity;
import com.szh.cloud.mybatis.entity.PtUserEntity;
import com.szh.cloud.user.entity.UserEntity;
import com.szh.cloud.user.execption.RepeatEmailException;
import com.szh.cloud.user.execption.RepeatMobileException;
import com.szh.cloud.user.execption.RepeatUserNameException;
import com.szh.cloud.user.service.UserService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private LoginDao loginDao;
    @Resource
    private UserService userService;

    @Override
    public PtUserEntity queryUserInfoByName(String username) {

        return loginDao.queryUserInfoByName(username);
    }

    @Override
    public List<MenuLevelEntity> queryMenuList() {
        String lang = LocaleContextHolder.getLocale().toString();
        LoginUserEntity entity = (LoginUserEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userUuid = entity.getUserUuid();
        List<PtMenuEntity> ptMenuEntities = loginDao.queryMenuList(userUuid, lang);
        //将数据菜单列表 转变了 等级菜单
        List<MenuLevelEntity> levelEntityList = new ArrayList<>();
        MenuLevelEntity menuLevelEntity;
        for(PtMenuEntity ptMenuEntity:ptMenuEntities){
            menuLevelEntity = new MenuLevelEntity(ptMenuEntity);
            levelEntityList.add(menuLevelEntity);
        }

        //找父亲节点
        List<MenuLevelEntity> rootEntityList = new ArrayList<>();
        boolean findParent = false;
        for(MenuLevelEntity child:levelEntityList){

            findParent = false;
            for(MenuLevelEntity parent:levelEntityList){
                if(child.getParentId().equals(parent.getMenuId())){
                    findParent = true;
                    parent.addChildList(child);
                    break;
                }
            }

            if(!findParent){
                rootEntityList.add(child);
            }

        }
        return rootEntityList;
    }

    @Override
    public List<String> queryAuthList(String userUuid) {
        return loginDao.queryAuthList(userUuid);
    }

    @Override
    public PtUserEntity queryUserListById(String userUuid) {
        return userService.queryUserListById(userUuid);
    }

    @Override
    public void modifyUserInfo(UserEntity userEntity) throws RepeatEmailException, RepeatUserNameException, RepeatMobileException {
        userService.modifyUserInfo(userEntity);
    }
}
